<template>
  <div style="padding:30px;">
    <el-form :inline="true" :model="form" class="demo-form-inline">
      <el-form-item label="供应商名称">
        <el-input v-model="form.name" clearable placeholder="供应商名称"></el-input>
      </el-form-item>
      <el-form-item label="供应商地址">
        <el-input v-model="form.address" clearable placeholder="供应商地址"></el-input>
      </el-form-item>
      <!-- <el-form-item label="供应商状态">
        <el-select v-model="form.state" clearable placeholder="请选择">
          <el-option label="启用" value="1"></el-option>
          <el-option label="停用" value="0"></el-option>
        </el-select>
      </el-form-item> -->

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="onSubmit">查询</el-button>
      </el-form-item>
    </el-form>
    <el-col :span="3">
      <el-button plain size="small" icon="el-icon-plus" type="primary" @click="adds()">新增</el-button>
    </el-col>
    <el-table ref="filterTable" :data="tableData" style="width: 100%">
      <el-table-column prop="name" label="供应商名称" width="180"></el-table-column>
      <el-table-column prop="typeName" label="进货商品类型" width="180"></el-table-column>
      <el-table-column prop="address" label="地址" width="180"> </el-table-column>
      <el-table-column prop="phone" label="电话" width="180"></el-table-column>
      <el-table-column prop="remark" label="备注" width="180"></el-table-column>
      <!-- <el-table-column prop="state" label="状态" width="width: 20%">
        <template slot-scope="scope">
          <el-tag :type="scope.row.state == '0' ? 'danger' : 'primary'" disable-transitions>
            {{scope.row.state==0?'停用':'启用'}}
          </el-tag>
        </template>
      </el-table-column> -->
      <input prop="id" label="供应商编号" type="hidden"/>
      <el-table-column label="操作" align="center" width="200px">
        <template slot-scope="scope">
          <el-button fixed="right" type="text" icon="el-icon-edit" size="small"
                @click="updateSupplier(scope.row)">编辑</el-button>
          <el-button type="text" icon="el-icon-edit" size="small"
                @click="supplierPro(scope.row)">分配商品</el-button>
          <el-button type="text" icon="el-icon-delete" size="small"
                @click="delSupplier(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="block">
      <!-- <el-tag class="demonstration">调整每页显示条数</el-tag> -->
      <el-pagination
       background layout="sizes,prev, pager, next"
       :total="count"
       :page-sizes="[4, 5, 6, 7]"
       :page-size="4"
       @current-change="showByLimit"
       @size-change="handleSizeChange">
      </el-pagination>
    </div>

    <!--添加 -->
    <el-dialog
        title="新增供应商"
         v-dialogDrag
         :close-on-click-modal="false"
         :modal="false"
         :visible.sync="addshow">
      <el-form :model="addform"
         :inline="true"
         class="demo-form-inline"
         :label-position="weizhi"
         :rules="rules"
          ref="addform"
         label-width="120px">
        <el-form-item label="供应商名称" prop="name">
          <el-input v-model="addform.name" clearable placeholder="供应商名称" prop="name"></el-input>
        </el-form-item>
        <el-form-item label="商品类型" prop="typeId">
         <!-- <el-select v-model="addform.typeId" clearable placeholder="请选择商品类型">
            <el-option v-for="item in showType" :key="item.id" :label="item.name" :value="item.id" />
          </el-select> -->
          <el-cascader
               :props="{value:'id',label:'name',children:'children'}"
               :options="showType"
               v-model="addform.typeId"
               :value-key="addform.typeId"
               :value="showType.id"
               :key="showType.id"
               :clearable="true"
               :show-all-levels="false"
               filterable
               clearable
               @change="addhandleChange"></el-cascader>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="addform.address" clearable placeholder="地址"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="addform.phone" clearable placeholder="电话"></el-input>
        </el-form-item>
        <!-- <el-form-item label="状态" prop="state">
          <el-select v-model="addform.state" clearable placeholder="请选择供应商状态">
            <el-option label="启用" value="1"></el-option>
            <el-option label="停用" value="0"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="addform.remark" clearable placeholder="备注"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="pushs('addform')">提 交</el-button>
        <el-button @click="reset('addform')">重 置</el-button>
      </div>
    </el-dialog>
    <!-- 修改-->
    <el-dialog
         title="修改供应商"
          v-dialogDrag
          :close-on-click-modal="false"
          :modal="false"
         :visible.sync="updateshow">
      <el-form :model="updateform" :inline="true" class="demo-form-inline" label-width="120px">
        <el-form-item label="供应商名称">
          <el-input v-model="updateform.name" clearable placeholder="供应商名称"></el-input>
        </el-form-item>
        <el-form-item label="商品类型">
          <!-- <el-select v-model="updateform.typeId" clearable placeholder="请选择商品类型">
            <el-option v-for="item in showType" :key="item.id" :label="item.name" :value="item.id" />
          </el-select> -->
          <el-cascader
               :props="{value:'id',label:'name',children:'children'}"
               :options="showType"
               v-model="updateform.typeId"
               :clearable="true"
               :value-key="updateform.typeId"
               :value="showType.id"
               :key="showType.id"
               :show-all-levels="false"
               clearable
               @change="updhandleChange"></el-cascader>
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="updateform.address" clearable placeholder="地址"></el-input>
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="updateform.phone" clearable placeholder="电话"></el-input>
        </el-form-item>
       <!-- <el-form-item label="状态">
          <el-select v-model="updateform.state" clearable placeholder="请选择供应商状态" value-key="updateform.state">
            <el-option label="启用" :value="1" :key="1"></el-option>
            <el-option label="停用" :value="0" :key="0"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="备注">
          <el-input v-model="updateform.remark" clearable placeholder="备注"></el-input>
        </el-form-item>
        <el-input v-model="updateform.id" type="hidden"></el-input>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updatepush()">提 交</el-button>
        <el-button @click="err()">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="商品分配" :visible.sync="suppliersp">
    <el-transfer
    	 v-model="value1"
    	 :titles="['未拥有', '已拥有']"
       @change="handleChange"
    	 :props="{key:'id',label:'name'}"
    	 :data="supplierproduct">
    </el-transfer>
    </el-dialog>

  </div>
</template>

<script>
  import {show,add,update,del} from '@/api/supplier'
  import {showType} from '@/api/producttype'
  import {showList,addsp,delsp} from '@/api/supplierProduct.js'
  import {showsp} from '@/api/product'

  export default {
    data() {
      return {
        supplierproduct:[],//给供应商分配商品
        //查询
        form: {
          name: '',
          address: '',
          state: ''
        },
        //分页
        page: 1,
        limit: 4,
        tableData: [],
        count: 4,
        addshow: false,
        //添加
        addform: {
          name: '',
          typeId: '',
          address: '',
          phone: '',
          remark: '',
          state: ''
        },
        addType:'',//重新定义一下在add添加方法时的商品类别的参数
        weizhi: 'right',//表单域标签位置
        showType: [],
        value:[],//商品类别数组
        value1:[],//商品回显
        supplierId:'',//供应商id
        suppliersp:false, //分配商品

        //编辑
        updateshow: false,
        updateform: {
          id: '',
          name: '',
          typeId: '',
          address: '',
          phone: '',
          remark: '',
          state: ''
        },
        updType:'',//重新定义一下在update编辑方法时的商品类别的参数
         //表单验证
          rules: {
            name: [
              { required: true, message: '请输入供应商名称', trigger: 'blur' }
            ],
            typeId: [
              { required: true, message: '请选择进货类型', trigger: 'change' }
            ],
            address: [
              { required: true, message: '请输入地址', trigger: 'blur' }
            ],
            phone: [
              { required: true, message: '请输入手机号', trigger: 'blur' }
            ]
            /* state: [
              { required: true, message: '请选择状态', trigger: 'change' }
            ] */
          },
          isLimit:false,
      }
    },
    //钩子函数
    created() {
     //获取商品类别
     showType({'typeName':1}).then((res)=>{
     // 循环遍历json数据
     this.showType=this.childrens(res.data);
     });
      this.showByLimit(1);
    },

    methods: {
      //分页查询所有
      showByLimit(val) { // 修改当前页所触发的函数
        return new Promise((resolve, reject) => {
          show({
            'limit': this.limit,
            'page': val,
            'address': this.form.address,
            'state': this.form.state
          }).then(response => {
            const {
              data,
              count
            } = response
            this.tableData = data;
            this.count = count;
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      },
      //循环删除选择器最后一个空数据
      childrens(show){
        let childs=show;
        for (var i = 0; i < childs.length; i++) {
          if (childs[i].children.length) {
              // children若为空数组，则将children设为undefined
              this.childrens(childs[i].children);
          }else{
            delete show[i].children;
          }
        }
        return show;
      },
      //当limit修改时分页查询所有
      handleSizeChange(val) {
        this.limit=val;
         if(this.isLimit){
          return new Promise((resolve, reject) => {
            show({
              'limit': val,
              'page': 1,
              'address': this.form.address,
              'state': this.form.state,
            }).then(response => {
              const {data,count} = response
              this.tableData = data;
              this.count = count;
              resolve()
            }).catch(error => {
              reject(error)
            })
          })
        }else{
         return new Promise((resolve, reject) => {
           show({'limit': val,'page': this.page}).then(response => {
             const {data,count} = response
             this.tableData = data;
             resolve()
           }).catch(error => {
             reject(error)
           })
         })
        }
      },
      //模糊查询表单提交
      onSubmit() {
        return new Promise((resolve, reject) => {
          show({
            'limit': this.limit,
            'page': this.page,
            'name': this.form.name,
            'address': this.form.address,
            'state': this.form.state
          }).then(response => {
            const {
              data,
              count
            } = response
            this.tableData = data;
            this.count = count;
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      },
      //添加按钮事件
      adds() {
        this.addshow = true;
      },
      //取消让弹框隐藏
      err() {
        this.addshow = false;
        this.updateshow = false;
        this.suppliersp= false;
      },
      updateSupplier(row) {
        this.updateshow = true;
        this.updateform = row;
        this.updateform.state = row.state;
      },
      //分配商品
      supplierPro(row){
        this.value1=[];
        this.suppliersp=true;
        this.supplierId=row.id;
        showsp({}).then(response => {
        this.supplierproduct=response.data;
        });
        /* console.log(this.supplierproduct); */
       showList({'supplierId':row.id}).then(respo => {
        	for(let i=0;i<respo.data.length;i++){
      		this.value1.push(respo.data[i].id);
      	}
        });
      },
      //批量分配、移出商品
     handleChange(value1, direction, movedKeys) {
           /* console.log(value1);
           console.log(direction);
           console.log(movedKeys); */
           if(direction=="left"){
           	delsp({'namelist':movedKeys,'typeName':this.supplierId}).then((res)=>{
           		if (res.data) {
           this.$message({
             showClose: true,
             message: res.msg,
             type: 'success',
             onClose:  () =>{
                this.err();
                this.showByLimit();
             }
           });
         } else {
         	this.$message({
             showClose: true,
             message: res.msg,
             type: 'error'
           });
         }
           	})
           }else{
           	addsp({'namelist':value1,'typeName':this.supplierId}).then((res)=>{
           		if (res.data) {
           this.$message({
             showClose: true,
             message: res.msg,
             type: 'success',
             onClose:  () =>{
                 this.err();
                 this.showByLimit();
             }
           });
         } else {
         	this.$message({
             showClose: true,
             message: res.msg,
             type: 'error'
           });
         }
           	})
           }
           this.supplierproduct.id = movedKeys;//文件列表的id数组
     },

      //提交添加
      pushs(formName) {
         //表单验证方法
        this.$refs[formName].validate((valid) => {
          if (valid) {
            return new Promise((resolve, reject) => {
              add({
                'name': this.addform.name,
                'typeId': this.addType,
                'address': this.addform.address,
                'phone': this.addform.phone,
                'remark': this.addform.remark,
                'state': this.addform.state
              }).then(response => {
                if(response.data){
                  this.$message({
                      message: response.msg,
                      type: 'success',
                      code: 1500,
                    onClose:  () =>{
                      location.reload();
                    }
                  });
                  }else{
                    this.$message({
                        showClose: true,
                        message: response.msg,
                        type: 'error',
                        code: 1500,
                   });
                  }
                resolve()
              }).catch(error => {
                reject(error)
              })
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      //添加时
      addhandleChange(value){
        console.log(value);
        this.addType=value[value.length-1];
        console.log(this.addType);
      },
      //编辑时
      updhandleChange(value){
        console.log(value);
        this.updType=value[value.length-1];
        console.log(this.updType);
      },

      //提交修改
      updatepush() {
        return new Promise((resolve, reject) => {
          update({
            'id': this.updateform.id,
            'name': this.updateform.name,
            'typeId': this.updType,
            'address': this.updateform.address,
            'phone': this.updateform.phone,
            'remark': this.updateform.remark,
            'state': this.updateform.state
          }).then(response => {
            console.log(response);
            if (response.data) {
              this.$message({
                message: response.msg,
                type: 'success',
                code: 1500,
               onClose:  () =>{
                 location.reload();
               }
              });
            } else {
              this.$message({
                showClose: true,
                message: response.msg,
                type: 'error'
              });
            }
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      },
      //删除
      delSupplier(row) {
        this.$confirm('此操作将永久删除该商品, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(response => {
          return new Promise((resolve, reject) => {
            del({
              'id': row.id
            }).then(response => {
              if (response.data) {
                this.$message({
                  message: response.msg,
                  type: 'success',
                  code: 1500,
                  onClose: () => {
                    location.reload();
                  }
                });
              } else {
                this.$message.error(response.msg);
              }
              resolve()
            }).catch(error => {
              reject(error)
            })
          })
          resolve()
        }).catch(error => {
          reject(error)
        })
      },
      clearFilter() {
        this.$refs.filterTable.clearFilter();
      },
      filterTag(value, row) {
        return row.state === value;
      },
      //添加重置
      reset(addform) {
         this.$refs[addform].resetFields();
       }
    }
  }
</script>
